/*
 * @Author       : xiangmin
 * @File         : url同步查询条件，https://juejin.cn/post/7353271369540501544
 * @Date         : 2024-04-07 11:30:25
 * @LastEditors  : xiangmin
 * @LastEditTime : 2024-04-08 10:25:51
 */
import qs from 'query-string'

export default function useUrlState(initialState = {}) {
	const urlState = ref({})
	function updateUrl() {
		const queryString = qs.stringify(urlState.value)
		const newUrl = new URL(window.location.href)
		newUrl.search = queryString
		history.pushState({}, '', newUrl.href)
	}

	urlState.value = { ...initialState }
	if (location.search) {
		// 删除第一个？字符串;
		const searchString = location.search.slice(1)
		// 解析url参数
		const searchParse = qs.parse(searchString)
		urlState.value = { ...urlState.value, ...searchParse }
	}
	updateUrl()

	function setSearch(newState) {
		urlState.value = { ...urlState.value, ...newState }
		updateUrl()
	}

	// watch(urlState, updateUrl)

	return { urlState, setSearch }
}
